//
//  DBNetworkLogController.m
//  AFNetworking
//
//  Created by HaiOu on 2019/11/8.
//

#import "DBNetworkLogController.h"
#import "DBNetworkLogDetailController.h"
#import "DBNetworkLogDataBase.h"
#import "Masonry.h"

NS_ASSUME_NONNULL_BEGIN

@interface DBNetworkLogTableViewCell : UITableViewCell

@property (nonatomic, strong) DBNetworkLogModel *model;

@end

NS_ASSUME_NONNULL_END

@interface DBNetworkLogController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@end

@implementation DBNetworkLogController {
    NSArray<DBNetworkLogModel *> *datas;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configInit];
    [self configUI];
}

- (void)configInit {
    datas = [DBNetworkLogDataBase queryAllNetworkLog];
}

- (void)configUI {
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIBarButtonItem *clear = [[UIBarButtonItem alloc] initWithTitle:@"Clear" style:UIBarButtonItemStylePlain target:self action:@selector(clearHistoricalRecords)];
    [clear setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:16]} forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = clear;
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (void)clearHistoricalRecords {
    [DBNetworkLogDataBase deleteAllNetworkLog];
    datas = nil;
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DBNetworkLogDetailController *vc = [[DBNetworkLogDetailController alloc] init];
    vc.model = datas[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return datas.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *kCell = @"kCell";
    DBNetworkLogTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCell];
    if (!cell) {
        cell = [[DBNetworkLogTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCell];
    }
    cell.model = datas[indexPath.row];
    return cell;
}

#pragma mark - Lazy Loading

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorInset = UIEdgeInsetsZero;
        //_tableView.rowHeight = 66.f;
        _tableView.sectionFooterHeight = CGFLOAT_MIN;
        _tableView.sectionHeaderHeight = CGFLOAT_MIN;
        CGFloat safeBottonDistance = 0.f;
        if (@available(iOS 11.0, *)) {
            safeBottonDistance = [[[UIApplication sharedApplication] delegate] window].safeAreaInsets.bottom;
        }
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, safeBottonDistance)];
    }
    return _tableView;
}

@end

@interface DBNetworkLogTableViewCell ()
@property (nonatomic, strong) UILabel *methodLabel;
@property (nonatomic, strong) UILabel *dateLabel;
@property (nonatomic, strong) UILabel *urlLabel;
@end

@implementation DBNetworkLogTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self configUI];
    }
    return self;
}

- (void)setModel:(DBNetworkLogModel *)model {
    _model = model;
    if (model.errorDescription.length > 0) {
        self.methodLabel.textColor = [UIColor redColor];
        self.dateLabel.textColor = [UIColor redColor];
        self.urlLabel.textColor = [UIColor redColor];
    } else {
        self.methodLabel.textColor = [UIColor blackColor];
        self.dateLabel.textColor = [UIColor blackColor];
        self.urlLabel.textColor = [UIColor lightGrayColor];
    }

    self.methodLabel.text = model.method;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM-dd HH:mm:ss"];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    NSString *dateStr = [formatter stringFromDate:model.date];
    self.dateLabel.text = dateStr;
    
    self.urlLabel.text = model.uriString;
}

- (void)configUI {
    UILabel *methodLabel = [[UILabel alloc] init];
    methodLabel.font = [UIFont boldSystemFontOfSize:14.f];
    methodLabel.textColor = [UIColor blackColor];
    self.methodLabel = methodLabel;
    [self.contentView addSubview:methodLabel];
    [methodLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12.f);
        make.top.mas_equalTo(5.f);
    }];

    UILabel *dateLabel = [[UILabel alloc] init];
    dateLabel.font = [UIFont boldSystemFontOfSize:14.f];
    dateLabel.textColor = [UIColor blackColor];
    dateLabel.textAlignment = NSTextAlignmentRight;
    self.dateLabel = dateLabel;
    [self.contentView addSubview:dateLabel];
    [dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(methodLabel);
        make.right.mas_equalTo(-12.f);
    }];
    
    UILabel *urlLabel = [[UILabel alloc] init];
    urlLabel.numberOfLines = 0;
    urlLabel.lineBreakMode = NSLineBreakByCharWrapping;
    urlLabel.font = [UIFont systemFontOfSize:14.f];
    urlLabel.textColor = [UIColor lightGrayColor];
    self.urlLabel = urlLabel;
    [self.contentView addSubview:urlLabel];
    [urlLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(methodLabel.mas_bottom).offset(3.f);
        make.left.mas_equalTo(12.f);
        make.right.mas_equalTo(-12.f);
        make.bottom.mas_equalTo(-5.f);
    }];
    
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
